﻿#include "networkcommunication.h"

#include <QtDebug>
#include <QJsonArray>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonDocument>

NetworkConnect *NetworkConnect::onlyone = nullptr;
QTcpSocket *NetworkConnect::conserver = nullptr;

NetworkConnect *NetworkConnect::connectserver()
{
    if(onlyone == nullptr)
        onlyone = new NetworkConnect();

    return onlyone;
}

void NetworkConnect::destroyThis()
{
    if(onlyone != nullptr)
        onlyone->deleteLater();
}

QTcpSocket *NetworkConnect::getconserver() const
{
    return conserver;
}

NetworkConnect::NetworkConnect(QObject *parent) : QObject(parent)
{
    conserver = new QTcpSocket (onlyone);
    conserver->connectToHost("1.14.252.79", 54321);

    isConnected = false;

    connect(conserver, SIGNAL(readyRead()), this, SLOT(handle()));
    connect(conserver, SIGNAL(disconnected()), this, SLOT(handledisconnect()));
    connect(conserver, SIGNAL(connected()), this, SLOT(handleconnected()));
}

bool NetworkConnect::isServerconnected() const
{
    return isConnected;
}

NetworkConnect::~NetworkConnect()
{
    conserver->close();
    onlyone->deleteLater();
    onlyone = nullptr;
    conserver = nullptr;
}

void NetworkConnect::handle()
{
    qDebug() << "有新的信息";
    mess = conserver->readAll();
    QJsonDocument js = QJsonDocument::fromJson(mess);
    if(!js.isObject())
    {
        qDebug() << __FILE__ << __LINE__ << "错误应答";
        qDebug() << mess;
    }
    QJsonObject obj = js.object();
    QString type = obj.value("type").toString();


    if(type == "user_signup")
    {
        qDebug() << "正在接收注册回发报文";
        emit user_signup(mess);
    }
    if(type == "user_signin")
    {
        qDebug() << "正在接收登录回发报文";
        emit user_signin(mess);
    }
    if(type == "getfriendslist")
    {
        qDebug() << "收到在线列表信息";
        emit getfriendslist(mess);
    }
    if(type == "forwardmsg")
    {
        qDebug() << "收到服务器转发信息";
        emit forwardmsg(mess);
    }
    if(type == "findpasswd")
    {
        emit findpasswd(mess);
    }
    if(type == "newclient")
    {
        emit newclient();
    }
}

void NetworkConnect::handledisconnect()
{
    qDebug() << "服务器断开连接";
}

void NetworkConnect::handleconnected()
{
    isConnected = true;
    qDebug() << "成功连接";
}
